package daoJPA;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

import dao.IPositionDAO;
import entityJPA.Position;

public class JPAPositionDAO implements IPositionDAO, Serializable {

	EntityManagerFactory emf;

	public JPAPositionDAO(EntityManagerFactory emf) {
		this.emf = emf;
	}

	public EntityManager getEntityManager() {
		return emf.createEntityManager();
	}

	@Override
	public void insert(Position pos) {
		// TODO Auto-generated method stub
		EntityManager em = null;
		try{
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(pos);
            em.getTransaction().commit();
		}finally{
			if(em!=null)
				em.close();
		}
	}

	@Override
	public void update(Position pos) {
		// TODO Auto-generated method stub
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.merge(pos); 
            em.getTransaction().commit();
            
        }finally{
        	if(em!=null)
        		em.close();
        }
	}

	@Override
	public void delete(Position pos) {
		// TODO Auto-generated method stub
		EntityManager em = null;
		try {
			em = getEntityManager();
			em.getTransaction().begin();
			Position p=em.getReference(Position.class, pos.getIdPosition());
			p.getPositionstatus().setValue("inactive");
			em.merge(pos);
			em.getTransaction().commit();

		} finally {
			if (em != null) {
				em.close();
			}
		}
	}

	@Override
	public Position findById(int  id) {
		// TODO Auto-generated method stub

		EntityManager em = null;
		try {
			em = getEntityManager();
			em.getTransaction().begin();
			return em.find(Position.class, id);
		} finally {
			if(em!=null)
				em.close();
		}
	}

	@Override
	public List<Position> findAll() {
		// TODO Auto-generated method stub
		EntityManager em = getEntityManager();
		Query q = null;
		try {
			CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
			cq.select(cq.from(Position.class));
			q = em.createQuery(cq);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return q.getResultList();
	}

}
